<!DOCTYPE html>
<html>
  <head>
    <title>Embedded Webchat</title>
    <!-- Set the base URL to access this page, for example: /botpress/
    It must match the path configured as an externalUrl in Botpress config, and in the init method -->
    <link rel="stylesheet" href="/assets/modules/channel-web/examples/parent.css" type="text/css" />
    <base href="/" />
    <!-- Object.assign polyfill (required for IE) -->
    <script src="assets/modules/channel-web/object_assign.js"></script>
    <script src="assets/modules/channel-web/inject.js"></script>
  </head>

  <body>
    <h1>Webchat Embedding Example</h1>
    <p>This is an example of embedded webchat. Try adding your "botId" as a URL parameter.</p>
    <p>
      Example:
      <code><span id="origin"></span>/assets/modules/channel-web/examples/embedded-webchat.html?botId=test</code>
    </p>
    <h2>
      Custom buttons
    </h2>
    <p>
      You can control the webchat visibility programmatically using the Webchat SDK. Moreover, you can listen for
      webchat events to detect if the webchat is opened or closed. In this example, the Toggle button changes color when
      the webchat is open (red).
    </p>
    <button id="show-bp">Show</button>
    <button id="hide-bp">Hide</button>
    <button id="toggle-bp" style="background-color: green;">Toggle</button>
    <h2>Send Messages Programmatically</h2>
    <p>You can simulate the user typing a message programmatically.</p>
    <button id="send-message-bp">Send "Hello"</button>
    <h2>Update Webchat Configuration</h2>
    <p>You can change the webchat configuration at runtime.</p>
    <button id="change-config1-bp">Config 1</button>
    <button id="change-config2-bp">Config 2</button>
    <p>You can also change language</p>
    <button id="change-lang1-bp">Arabic</button>
    <button id="change-lang2-bp">French</button>
    <button id="change-lang3-bp">Browser (default)</button>
    <h2>Control User Identity</h2>
    <p>The current user ID is <span id="user-id-bp">UNKNOWN</span></p>

    <h2>Working with multiple chat windows</h2>
    <button id="show-second-bp">Toggle second chat window</button>
    <div id="chat2"></div>

    <script>
      function parseQuery(queryString) {
        const query = {}
        const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&')
        for (let i = 0; i < pairs.length; i++) {
          const pair = pairs[i].split('=')
          query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
        }
        return query
      }

      const params = parseQuery(window.location && window.location.search)
      const botId = (params && params.botId) || 'welcome-bot'

      let userId
      let webchatOpen = false

      let lastConfig = {
        host: window.location.origin || 'http://localhost:3000',
        botId: botId,
        lazySocket: false
        /*
        To change the styling of the webchat, you can either edit directly default.css, or use the extraStylesheet property.
        This allows you to customize the chat on a per-bot basis.
      */
        //extraStylesheet: 'assets/modules/channel-web/examples/my-theme.css'
      }

      window.botpressWebChat.init(lastConfig)

      document.getElementById('origin').innerText = window.location.origin

      document.getElementById('show-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'show' })
      })

      document.getElementById('hide-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'hide' })
      })

      document.getElementById('send-message-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'message', text: 'Hello!' })
      })

      document.getElementById('change-config1-bp').addEventListener('click', function() {
        Object.assign(lastConfig, {
          userId: userId,
          extraStylesheet: 'assets/modules/channel-web/examples/custom-theme.css',
          showConversationsButton: false,
          botName: 'Bot Config 1',
          botConvoDescription: 'Description of Bot Config 1',
          enableReset: false,
          enablePersistHistory: false,
          enableResetSessionShortcut: false
        })

        window.botpressWebChat.configure(lastConfig)
      })

      document.getElementById('change-config2-bp').addEventListener('click', function() {
        Object.assign(lastConfig, {
          userId: userId,
          extraStylesheet: null,
          showConversationsButton: true,
          botName: 'Bot Config 2',
          botConvoDescription: 'Description of Bot Config 2',
          enableReset: true,
          enablePersistHistory: true,
          enableResetSessionShortcut: true
        })

        window.botpressWebChat.configure(lastConfig)
      })

      document.getElementById('change-lang1-bp').addEventListener('click', function() {
        lastConfig.locale = 'ar'
        window.botpressWebChat.configure(lastConfig)
      })

      document.getElementById('change-lang2-bp').addEventListener('click', function() {
        lastConfig.locale = 'fr'
        window.botpressWebChat.configure(lastConfig)
      })

      document.getElementById('change-lang3-bp').addEventListener('click', function() {
        lastConfig.locale = 'browser'
        window.botpressWebChat.configure(lastConfig)
      })

      document.getElementById('toggle-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: webchatOpen ? 'hide' : 'show' })
      })

      let secondInit = false
      const secondChatId = 'second'
      function toggleChat2() {
        window.setTimeout(function() {
          window.botpressWebChat.sendEvent({ type: 'toggle' }, secondChatId)
        }, 100)
      }
      document.getElementById('show-second-bp').addEventListener('click', function() {
        if (secondInit) {
          toggleChat2()
          return
        }
        const config = {
          host: window.location.origin || 'http://localhost:3000',
          botId: botId,
          userId: Math.random()
            .toString()
            .slice(-25),
          showConversationsButton: false,
          botName: 'Chat window #2',
          className: 'chat2',
          enableReset: false,
          chatId: secondChatId,
          hideWidget: true,
          disableAnimations: true,
          containerWidth: 700,
          layoutWidth: 700,
          exposeStore: true
        }
        window.botpressWebChat.init(config, '#chat2')
        secondInit = true
      })

      window.addEventListener('message', function(message) {
        // chat2
        if (message.data.chatId === secondChatId) {
          if (message.data.name === 'webchatLoaded') {
            toggleChat2()
          }
        } else {
          // chat 1
          if (message.data.userId) {
            userId = message.data.userId
            document.getElementById('user-id-bp').innerText = userId
          }

          if (message.data.name === 'webchatOpened') {
            webchatOpen = true
            document.getElementById('toggle-bp').style.backgroundColor = 'red'
          }

          if (message.data.name === 'webchatClosed') {
            webchatOpen = false
            document.getElementById('toggle-bp').style.backgroundColor = 'green'
          }
        }
      })
    </script>
  </body>
</html>
